package com.wzh.project.redis.handle;

import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.wzh.project.redis.bean.RedisMessage;

public class RedisReplyHandler {
	private static final Logger logger=LogManager.getLogger(RedisReplyHandler.class);
	
	private static RedisReplyHandler init=new RedisReplyHandler();
	
	private RedisReplyHandler() {
		
	}
	
	public static RedisReplyHandler getInit() {
		return init;
	}
	/**
	 * 用于存放结果
	 */
	private Map<String,Object> resultMap=new HashMap<String,Object>();
	/**
	 * 用于存放加锁对象
	 */
	private Map<String,String> locksMap=new HashMap<String,String>();
	
	public Map<String,String> getLocksMap(){
		return locksMap;
	}
	
	/**
	 * 发送之后开启等待
	 * @param uuid
	 * @param timeout
	 * @return
	 * @throws Exception
	 */
	public Object handle(String uuid,long timeout) throws Exception {
		synchronized (uuid) {
			long t1=System.currentTimeMillis();
			logger.debug("开始等待接收回复消息");
			if (resultMap.get(uuid)==null) {
				uuid.wait(timeout);
			}
			Object result=resultMap.remove(uuid);
			long t2=System.currentTimeMillis();
			logger.debug("接收到回复消息，共消耗了："+(t2-t1)/1000+"s");
			if(result==null) {
				logger.debug("超时异常");
				throw new Exception("超时异常");
			}else {
				return ((RedisMessage)result).getObj();
			}
		}
	}
	
	/**
	 * 接收到回复消息进行处理,通知等待方从结果中获取消息
	 */
	public void dealResponse(String uuid,Object message) {
		long t1=System.currentTimeMillis();
		String lock=locksMap.get(uuid);
		if (lock==null) {
			return ;
		}
		synchronized (lock) {
			resultMap.put(uuid, message);
			lock.notify();
		}
		long t2=System.currentTimeMillis();
		logger.debug("dealResponse 耗时："+(t2-t1)/1000+"s");
	}
}
